package com.example.myprojectoffeixue;

import android.app.Activity;

import java.lang.annotation.Annotation;
import java.lang.reflect.Field;

public final class Interpretor {
    private final Activity mActivity;

    private Interpretor(Activity activity) {
        mActivity = activity;
    }

    /**
     * Gets an {@link Interpretor} capable of injecting fields for the given
     * Activity.
     */
    public static Interpretor get(Activity activity) {
        return new Interpretor(activity);
    }

    public void inject() {
        for (Field field : mActivity.getClass().getDeclaredFields()) {
            for (Annotation annotation : field.getAnnotations()) {
                if (annotation.annotationType().equals(InterpretView.class)) {
                    try {
                        Class<?> fieldType = field.getType();
                        int idValue = InterpretView.class.cast(annotation).value();
                        field.setAccessible(true);
                        Object injectedValue = fieldType.cast(mActivity
                                .findViewById(idValue));
                        if (injectedValue == null) {
                            throw new IllegalStateException("findViewById("
                                    + idValue + ") gave null for " + field
                                    + ", can't inject");
                        }
                        field.set(mActivity, injectedValue);
                        field.setAccessible(false);
                    } catch (IllegalAccessException e) {
                        throw new IllegalStateException(e);
                    }
                }
            }
        }
    }
}
